import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_imageannotation/map-bottom-btns.dart';
import 'package:flutter_imageannotation/map-marker-widget.dart';
import 'package:flutter_imageannotation/utils.dart';

import 'map-marker.dart';

class MapWithMarkers extends StatefulWidget {
  @override
  _MapWithMarkersState createState() => _MapWithMarkersState();
}

class _MapWithMarkersState extends State<MapWithMarkers> {
  final TransformationController _transformationController  = TransformationController();
  List<MapMarker> markers = []; //标注集合
  bool showMarkerPop = false; // 是否显示标注的pop,
  MapMarker? _selectedMarker; //当前选中的标注
  bool _mapIsDragging = false; //地图是否在拖拽中
  bool _mapMarkerIsDragging = false; //标注是否在拖拽中
  final bool _enableDrag = true; //标注是编辑标注
  bool _mapPanEnabled = true; //是否可以拖拽平移地图
  MapMode currentMode = MapMode.view;

  Offset? currentTapDownOffset;


  void _addMarker(Offset position) {
    currentTapDownOffset = null;
    setState(() {
      markers.add(MapMarker(position, 'Location ${markers.length + 1}'));
    });
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      //将图片至于屏幕的中间
      getImageSize(assetPath: 'images/map.png').then((imageSize){
         // 初始化地图的变换矩阵，使其居中并放大0.5倍
        WidgetsBinding.instance.addPostFrameCallback((_) {
          final RenderBox renderBox = context.findRenderObject() as RenderBox;
          final Size viewerSize = renderBox.size;
          final double imageWidth = imageSize.width; // 图片宽度
          final double imageHeight = imageSize.height; //图片高度
          double translateX = 0.0;
          double translateY = 0.0;
          if (imageWidth > viewerSize.width) {
            translateX = (imageWidth - viewerSize.width) / 2;
          }
          if (imageHeight > viewerSize.height) {
            translateY = (imageHeight - viewerSize.height) / 2;
          }
          _transformationController.value = Matrix4.identity()
            ..translate(-translateX, -translateY);
        });
      });
    });
  }

  // 处理地图的点击按下事件 (记录当前的位置信息)
  void _onMapTapDown(TapDownDetails details) {
    // 获取相对于 InteractiveViewer 的坐标
    Offset globalPosition = details.globalPosition;
    Offset localPosition = _globalToLocal(globalPosition);
    currentTapDownOffset = localPosition;
  }

  // 处理地图的点击抬起事件
  void _onMapTapUp(){
    Future.delayed(const Duration(milliseconds: 100), () {
      //不是拖拽或者缩放地图
      if (!_mapIsDragging && !_mapMarkerIsDragging && currentMode==MapMode.add && currentTapDownOffset!=null) {
        _addMarker(currentTapDownOffset!);
      }
    });
  }

  // 处理标注的点击事件
  void _onMarkerTap(MapMarker marker) {
    _mapIsDragging = false;
    if (!_mapIsDragging) {
      setState(() {
        _selectedMarker = marker;
      });
    }
  }

  // 处理标注的点击取消事件
  void _onMarkerTapCancel(MapMarker marker) {
    setState(() {
      _mapIsDragging = false;
      _mapMarkerIsDragging = false;
      _mapPanEnabled = true;
    });
  }

  //处理标注开始拖拽时的处理 禁止地图拖拽
  void _onMarKerDragStarted(MapMarker marker,[TapDownDetails? details]){
    print("__onMarKerDragStarted===>$marker====>_mapIsDragging==>$_mapIsDragging");
     _mapIsDragging = false;
    if (!_mapIsDragging) {
      setState(() {
        _selectedMarker = marker;
        _mapMarkerIsDragging = true;
        _mapPanEnabled = false;
      });
    }
  }

  //处理标注拖拽结束时的处理 更信位置信息
  void _onMarKerDragEnd(details,marker){
      // 获取相对于 InteractiveViewer 的坐标
      Offset globalPosition = details.offset;
      Offset localPosition = _globalToLocal(globalPosition);
      setState(() {
         marker.position = localPosition;
        _mapPanEnabled = true;
        _mapMarkerIsDragging = false;
      });
  }

  // 将全局坐标转换为本地坐标
  Offset _globalToLocal(Offset globalPosition) {
    //获取全局点击位置
    // 获取 RenderBox
    RenderBox renderBox = context.findRenderObject() as RenderBox;
    // 将全局坐标转换为本地坐标
    Offset localPosition = renderBox.globalToLocal(globalPosition);
    // 获取当前的变换矩阵
    Matrix4 transform = _transformationController.value;
    // 获取逆变换矩阵
    Matrix4 inverseTransform = Matrix4.inverted(transform);
    // 将点击位置转换为 InteractiveViewer 的本地坐标
    Offset transformedPosition = MatrixUtils.transformPoint(inverseTransform, localPosition);
    return transformedPosition;
  }

  //底部图标点击
  void _onBottomBtnClick(MapMode mode){
    if(currentMode == mode){
      return;
    }
    setState(() {
      currentMode = mode;
    });
  }

  @override
  Widget build(BuildContext context) {
      return Column(
          children: [
            Expanded(
              child: InteractiveViewer(
                transformationController: _transformationController,
                constrained: false,
                minScale: 0.3,
                maxScale: 3.0,
                panEnabled: _mapPanEnabled,
                onInteractionStart: (_) {
                  setState(() { _mapIsDragging = true; });
                },
                onInteractionEnd: (_) {
                  setState(() { _mapIsDragging = false; });
                },
                child:Stack(
                  children: [
                    GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTapDown: _onMapTapDown,
                      onTap:_onMapTapUp ,
                      onLongPress:() => {
                        setState(() { _mapIsDragging = true; })
                      },
                      onLongPressEnd: (LongPressEndDetails details) {
                        setState(() { _mapIsDragging = false; });
                      },
                      child: ColorFiltered(
                        colorFilter: ColorFilter.mode(
                          Colors.black.withOpacity(currentMode ==MapMode.view ? 0 : 0.65), // 遮罩颜色和透明度
                          BlendMode.srcATop,
                        ),
                        child: Image.asset('images/map.png',fit: BoxFit.contain),
                      )
                    ),
                    //渲染标注
                     for (var marker in markers)
                        MapMarkerWidget(
                          marker:marker,
                          enableDrag:true,
                          markerTapDownCallback: _onMarKerDragStarted,
                          markerTapUpCallback: _onMarkerTap,
                          markerTapCancelCallback: _onMarkerTapCancel,
                          markerDragStarted: _onMarKerDragStarted,
                          markerDragEnd: _onMarKerDragEnd,
                        ),
                    // 标注

                    //遮罩层
                ],

            )
          ),
        ),
        MapBottomBtns(currentMode:currentMode,onBottomBtnClick:_onBottomBtnClick)
      ]
    );
  }
  Widget _buildPopup(MapMarker marker) {
    return Positioned(
      left: marker.position.dx,
      top: marker.position.dy - 100,
      child: Container(
        decoration:const BoxDecoration(
          	shape: BoxShape.rectangle,
            borderRadius: BorderRadius.all(Radius.circular(20)),
              color: Colors.black87
           ),
      ));
  }
}